package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService{

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void insert(Employee employee, Long[] ids) {
        //对密码进行加密,用户名加盐
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(),employee.getName());
        employee.setPassword(md5Hash.toString());
        employeeMapper.insert(employee);
        //关联关系
        if (ids != null && ids.length >0){
            for (Long rid : ids){
                employeeMapper.insertRelation(employee.getId(),rid);
            }
        }
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除关系
        employeeMapper.deleteRelation(employee.getId());
        //关联关系,批量插入
        if (ids != null && ids.length >0){
            for (Long rid : ids){
                employeeMapper.insertRelation(employee.getId(),rid);
            }
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteRelation(id);
    }

    @Override
    public Employee get(Long id) {
       return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {

        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.queryForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {

        if (!StringUtils.hasText(username)){
            throw new LogicException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)){
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.checkByUsernameAndPassword(username,password);
        if (employee == null){
            throw new LogicException("用户名和密码错误");
        }
        if (!employee.isStatus()){
            throw new LogicException("用户禁用,请联系管理员");
        }
        return employee;
    }

    @Override
    public void updatePwdByIdAndOldPwd(Long id,String oldPassword,String newPassword) {

        //获取当前登录用户
        Employee employee = UserContext.getCurrentUser();
        if (id == null){
            throw new LogicException("登录用户id为空");
        }
        if (!StringUtils.hasText(oldPassword)){
            throw new LogicException("原密码不能为空");
        }
        if (!StringUtils.hasText(newPassword)){
            throw new LogicException("新密码不能为空");
        }
        if (!employee.getPassword().equals(oldPassword)){
            throw new LogicException("原密码不正确");
        }
        employeeMapper.updatePwdByIdAndOldPwd(id,oldPassword,newPassword);
    }

    @Override
    public void resetPwdByAdmin(String newPassword, Long id) {
        if (id == null){
            throw new LogicException("用户id为空");
        }
        if (!StringUtils.hasText(newPassword)){
            throw new LogicException("密码不能为空");
        }
        employeeMapper.resetPwdByAdmin(newPassword,id);
    }

    //改变状态
    @Override
    public void changeStatus(Long status, Long id) {
        employeeMapper.changeStatus(status,id);

    }

    @Override
    public Employee selectByName(String name) {

        Employee employee = employeeMapper.selectByName(name);
        return employee;
    }

    @Override
    public Workbook exportXls() {
        //查询所有员工
        List<Employee> employees = employeeMapper.selectAll();
        //使用poi创建一个excel
        Workbook wb = new HSSFWorkbook();
        //创建excel中的表
        Sheet sheet = wb.createSheet("员工信息表");
        //创建一行数据,从0开始
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        for (int i = 0;i < employees.size();i++){
            Employee employee = employees.get(i);
            //每个员工创建一行数据
            row = sheet.createRow(i+1);
            //创建单元格,写入内容到单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //读取上传的文件,并且封装为一个WorkBook对象
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读第0张sheet表
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //标题行不读,lastRowNum是代表索引,需要使用=
        for (int i = 1;i < lastRowNum;i ++){
            //获取每一行数据
            Row row = sheet.getRow(i);
            Employee employee = new Employee();
            /*if (row.getCell(0) == null || row.getCell(1) == null){
                break;  //判断空值问题,用户或邮箱有一个空值就不读取
            }*/
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            //判断单元格格式
            Cell cell = row.getCell(2);
            if (cell.getCellType() == CellType.NUMERIC){
                employee.setAge((int) cell.getNumericCellValue());
            }else {
                employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            }
            employeeMapper.insert(employee);
        }
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
        for (Long id : ids){
            employeeMapper.deleteRelation(id);
        }
    }

    @Override
    public List<Employee> selectByMaster() {

        List<Employee> employees = employeeMapper.selectByMaster();
        return employees;
    }

    @Override
    public List<Employee> selectByRoleSn(String[] sns) {
        List<Employee> employees = employeeMapper.selectByRoleSn(sns);
        return employees;
    }


}
